/*
 * @lc app=leetcode.cn id=160 lang=cpp
 *
 * [160] 相交链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        //一种很精妙的解法在于
        //第一个指针：a1->a2->c1->c2->c3->b1->b2->b3->c1
        //第二个指针: b1->b2->b3->c1->c2->c3->a1->a2->c1
        //如果不相交
        //a1->a2->b1->NULL
        //b1->a1->a2->NULL
        ListNode* l1 = headA, * l2 = headB;
        while(l1 != l2){
            l1 = (l1 == nullptr) ? headB : l1->next;
            l2 = (l2 == nullptr) ? headA : l2->next;
        }
        return l1;
    }
};
// @lc code=end

